<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { copyStepTaskApi } from '#/api/process/stepTask';

import { useCopySchema } from '../data';

const emit = defineEmits<{
  success: [];
}>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useCopySchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      modalApi.close();
      emit('success');
    }

    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      try {
        const input = {
          stepTaskId: data.stepTaskId,
          taskCodePrefix: data.taskCodePrefix,
          taskNamePrefix: data.taskNamePrefix,
          count: data.count,
        };
        await copyStepTaskApi(input);
        modalApi.close();
        emit('success');
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { id, taskName } = modalApi.getData<Record<string, any>>();
      formApi.setValues({ stepTaskId: id }, false);
      modalApi.setState({ title: `复制工步-${taskName}` });
    }
  },
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
